import 'dart:typed_data';
import 'package:inmotion_pro/utils/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:lx_widgets_library/utils/crypto_util.dart';
import 'package:encrypt/encrypt.dart' as encrypt;

// AES加密和解密工具类
// 该类用于加密4字节数据和当前时间戳，并提供解密功能
// 使用AES算法进行加密和解密
// 注意：密钥长度必须是16, 24或32字节
class TimestampEncryptor {
  final String secretKey;

  TimestampEncryptor({required this.secretKey}) {
    // 密钥长度必须是16, 24或32字节
    if (secretKey.length != 16 &&
        secretKey.length != 24 &&
        secretKey.length != 32) {
      throw ArgumentError('Secret key must be 16, 24, or 32 bytes long');
    }
  }

  // 加密方法：将4字节数据和当前时间戳一起加密
  String encryptWithTimestamp(List<int> fourBytes) {
    if (fourBytes.length != 4) {
      throw ArgumentError('Input must be exactly 4 bytes');
    }

    // 获取当前时间戳（秒级）
    final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;

    // 将timestamp转换为4字节（大端序）
    final timestampBytes = Uint8List(4)
      ..[0] = (timestamp >> 24) & 0xFF
      ..[1] = (timestamp >> 16) & 0xFF
      ..[2] = (timestamp >> 8) & 0xFF
      ..[3] = timestamp & 0xFF;

    return CryptoUtil.encrypter(
        Utils.uint8List2HexString(
            Uint8List.fromList([...fourBytes, ...timestampBytes])),
        secretKey);
  }

  // 解密方法：返回原始4字节数据和时间戳
  DecryptedResult decryptWithTimestamp(String encryptedBase64) {
    Uint8List decryptedBytes = Utils.hexString2Uint8List(
        CryptoUtil.decrypter(encryptedBase64, secretKey));

    if (decryptedBytes.length != 8) {
      throw ArgumentError(
          'Decrypted data must be 8 bytes (4 bytes data + 4 bytes timestamp)');
    }

    // 提取前4字节（原始数据）
    final originalData = decryptedBytes.sublist(0, 4);

    // 提取后4字节（时间戳）
    final timestampBytes = decryptedBytes.sublist(4, 8);
    // 将4字节时间戳转换为整数（大端序）
    final timestamp = (timestampBytes[0] << 24) |
        (timestampBytes[1] << 16) |
        (timestampBytes[2] << 8) |
        timestampBytes[3];
    return DecryptedResult(originalData, timestamp);
  }
}

class DecryptedResult {
  final List<int> originalData;
  final int timestamp;

  DecryptedResult(this.originalData, this.timestamp);

  // 获取时间戳对应的DateTime对象
  DateTime get dateTime =>
      DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

  @override
  String toString() {
    return 'Original Data: $originalData, Timestamp: $timestamp (${dateTime.toString()})';
  }
}

// 单独的AES加密类，用于加密字符串
class AESEncryptor {
  // 加密
  static String encrypter(String content) {
    String key = "5e5009171aaa489898f46a7a844c6432";
    // 生成一个随机的 IV (Initialization Vector)
    final iv = encrypt.IV.fromSecureRandom(16);
    // 创建加密器，使用 AES CFB 模式
    final encrypter = encrypt.Encrypter(
        encrypt.AES(encrypt.Key.fromUtf8(key), mode: encrypt.AESMode.ctr));
    // 加密
    final encrypted = encrypter.encrypt(content, iv: iv);
    List<int> list = [];
    Uint8List list1 = Uint8List.fromList(iv.bytes);
    Uint8List list2 =
        Uint8List.fromList(encrypted.bytes.sublist(0, content.length));
    list.addAll(list1);
    list.addAll(list2);
    return encrypt.Encrypted(Uint8List.fromList(list)).base64;
  }
}
